<?php


namespace Module\DyAi\Api\Controller;

use Illuminate\Routing\Controller;
use ModStart\Core\Dao\ModelUtil;
use ModStart\Core\Input\InputPackage;
use ModStart\Core\Input\Response;
use Module\DyAi\Model\DownContent;
use Module\DyAi\Model\DyAiZhuanji;
use Module\DyAi\Model\DyAiCategory;
use Module\DyAi\Model\DyAiKeysugg;
use DOMDocument;
use GuzzleHttp\Client;

/**
 * @Api 当游网专辑api接口
 */
class ZhuanjiController extends Controller
{

    /**
     * @Api 推送专辑编写ai内容
     */
    public function zj_ai_content()
    {
		try{
            $input = InputPackage::buildFromInput();
            $zj = DyAiZhuanji::whereNull('content')->where('status',0)->first();
            $url = 'http://gs2.3h3.com:8082/DyV2.aspx?api=GetAIToken';
            $client = new Client;
            $ai_role_id = 53;
            $response = $client->post($url,['form_params'=>['id'=>$ai_role_id,'did'=>6,'get_content'=>1]]);
            $json = json_decode($response->getBody(),true);
            $deps = json_decode($zj['dep_json'],true);
            $all_dep = DyAiCategory::all();
			$sub_texts = [];
            foreach($all_dep as $a_i=>$dep) {
                $ids = $deps[$dep['id']]['ids'];
                if(count($ids)==0)continue;
                $contents = [];
                $result = [];
                $downs = DownContent::whereIn('down_id',$ids)->where('categoryId',$dep['id'])->get(['title','softname','content','ai_json'])->toArray();
                foreach ($downs as $dk=>$d){
					$ai_json = json_decode($d['ai_json'],true);
					$result[] = ['sub_title'=>$zj['sub_title'],'scenarios'=>$ai_json['scenarios'],'audience'=>$ai_json['audience']];
					break;
                    //$ps = explode('</p>',$d['content']);
                    //$contents[] = ['softname'=>$d['softname']?$d['softname']:$d['title'],'content'=>trim(preg_replace('/\s+/', ' ', strip_tags($ps[0])))];
                }
                /*foreach($contents as $c){
                    //$result[] = ['sub_title'=>$zj['sub_title'],'softname'=>$c['softname'],'overview'=>$c['content']];
                }*/
                $text = json_encode($result,JSON_UNESCAPED_UNICODE);//提交到凤鑫ai角色那边组合内容
                /*$url = 'http://gs2.3h3.com:8082/DyV2.aspx?api=GetAIContent';
                $response = $client->post($url, [
                    'form_params' => [ // 使用 form_params 而不是 content，它会自动 URL 编码
                        'content' => $text,
                        'SubmitFormat' => 1,
                    ],
                    'headers' => [
                        'Content-Type' => 'application/x-www-form-urlencoded', // 明确设置 Content-Type
                    ],
                ]);
                $json2 = json_decode($response->getBody(), true);
                $text_json = $json2['datas'] ? $json2['datas'] : $text;*/
                //$content = $json['datas'][0]['token_json']['GPStartStr'] . $text_json;
				$content = $text;
                $url = 'http://gs2.3h3.com:1881/gpt';
                $post_arr = ['api' => 'gpt', 'token_id' => $ai_role_id, 'cuetip' => $json['datas'][0]['token_json']['GPStartStr'], 'content' => $content, 'CallBackUrl' => 'http://' . $_SERVER['HTTP_HOST'] . '/api/zhuanji/callback_zj_content?id=' . $zj['id'].'&depId='.$dep['id']];
                $response = $client->post($url, [
                    'json' => $post_arr,
                    'headers' => [
                        'Content-Type' => 'application/json', // 明确设置 Content-Type
                    ],
                ]);
				$json3 = json_decode($response->getBody(), true);
				$sub_texts[$dep['id']] = $content;
            }
			if(count($sub_texts)>0){
				$zj->sub_text = json_encode($sub_texts,JSON_UNESCAPED_UNICODE);
				$zj->status = 1;
				$zj->save();
			}
		}catch(\Exception $e){
            return Response::generateError($e->getMessage(). ' -> ' . $e->getTraceAsString());
		}
        return Response::generateSuccessData(['id'=>$zj['id']]);
    }

    /**
     * @Api 回调
     */
    public function callback_zj_content()
    {
        $input = InputPackage::buildFromInput();
        $SignMD5 = $input->getTrimString('SignMD5');
        $code = $input->getInteger('code');
        $id = $input->getInteger('id');
        $depId = $input->getInteger('depId');
		$result_content = $input->getTrimString('result_content');
        $content = str_replace(['```html','```'],'',$result_content);
        $zj = DyAiZhuanji::where(['id' => $id])->first();
        $dep_json = json_decode($zj['dep_json'],true);
		if($zj && $dep_json){
            $dep_json[$depId]['desc'] = trim(preg_replace('/\s+/', ' ', strip_tags($content)));
            $dep_json[$depId]['content'] = $content;
			$result = DyAiZhuanji::where('id', $zj['id'])->update(['status'=>2,'submit_fx_content' => ($result_content),'dep_json' => json_encode($dep_json,JSON_UNESCAPED_UNICODE)]);
		}
        return Response::generateSuccessData($result);
    }

    /**
     * @Api 获取专辑图
     */
    public function get_zj_image()
    {
        $input = InputPackage::buildFromInput();
        $SignMD5 = $input->getTrimString('SignMD5');
        $code = $input->getInteger('code');
        $id = $input->getInteger('id');
        $depId = $input->getInteger('depId');
        $img = $input->getTrimString('img');
        $zj = DyAiZhuanji::where(['id' => $id])->first();
        $dep_json = json_decode($zj['dep_json'],true);
        if($zj && $dep_json){
            $dep_json[$depId]['thumb'] = '';
            $dep_json[$depId]['zj_banner'] = '';
            $result = DyAiZhuanji::where('id', $zj['id'])->update(['dep_json' => json_encode($dep_json)]);
        }
        return Response::generateSuccessData($result);
    }

    /**
     * @Api 推送专辑到各个网站
     */
    public function send_zj()
    {
        $zj = DyAiZhuanji::where(['status' => 2])->first();
		$up_result = 0;
		$status = 99;
		$site_urls = [1=>'www.downxia.cn',2=>'www.3h3.com',3=>'www.87g.com',4=>'www.downxing.com',5=>'www.downwn.cn'];
        $site_urls = [5=>'www.autodownzj.cn'];
        if($zj){
			try{
				$is_up = false;
				$dep_json = json_decode($zj['dep_json'],true);//var_dump($dep_json);
				$client = new Client;
				foreach($dep_json as $dep=>$r){
					$dep= 5;
					if($r['content']){
						$is_up = true;
						$imgs = [];
						
						//$create_img = postUrl('http://'.$site_urls[3].'/zj_imagick/imagick.php',['imgs'=>$imgs,'path'=> $_SERVER['DOCUMENT_ROOT'].'/uploadfile','width'=>'624','height'=>'272']);
						//$img_url = $host.'zj_imagick/'.$create_img;
						
						$url = 'http://'.$site_urls[$dep].'/index.php?m=content&c=api&a=save_ai_zj';
                        $down_ids = $dep_json[$dep]['ids'];
						$downid = $down_ids[array_rand($down_ids)];
                        $down = DownContent::where('down_id',$downid)->where('categoryId',$dep)->first();
                        $typeid = $down->catid;
                        $ai_json = json_decode($down->ai_json,true);
                        $audience = $ai_json['audience'];
                        $scenarios = $ai_json['scenarios'];
                        $comprehensive_keywords = $ai_json['comprehensive_keywords'];
						$zj_catid = 61;
						$bwbb = '必备手机应用';if(strstr($zj['sub_title'],'游戏')){$bwbb = '必玩手机游戏';$zj_catid = 62;}
						$title = $zj['sub_title'].'-'.$audience[array_rand($audience)].$bwbb;//.'-'.$scenarios[array_rand($scenarios)];
						
                        //$result_ai_key = implode(',',$scenarios).','.implode(',',$audience).','.implode(',',$comprehensive_keywords);
						$result_ai_key = implode(',',$comprehensive_keywords);
						$dotPosition = strpos($dep_json[$dep]['desc'], '。');
						if ($dotPosition !== false) {
							$desc = substr($dep_json[$dep]['desc'], 0, $dotPosition).'。';
						}else{
							$desc = $dep_json[$dep]['desc'];
						}
                        $post_arr = ['zj_catid'=>$zj_catid,'sub_title'=>$zj['sub_title'],'title'=>$title,'tag'=>$zj['tag'],
						'keywords'=>$zj['keywords'],'description'=>$desc,'content'=>$dep_json[$dep]['content'],
						'thumb'=>$dep_json[$dep]['thumb'],'zj_banner'=>$dep_json[$dep]['zj_banner'],
						'down_ids'=>$down_ids,'typeid'=>$typeid,'result_ai_key'=>$result_ai_key];
						$response = $client->post($url, [
							'json' => $post_arr,
							'headers' => [
								'Content-Type' => 'application/json', // 明确设置 Content-Type
							],
						]);//echo $url;echo($response->getBody());
						$json = json_decode($response->getBody(), true);
						if($json['code'] == 200){$status = 99;$is_up = true;$dep_json[$dep]['status'] = 99;}else{$dep_json[$dep]['status'] = -1;}
					}
					//break;//测试用，需要注释
				}
				$up_result = DyAiZhuanji::where('id', $zj['id'])->update(['status' => $status,'dep_json'=>json_encode($dep_json)]);
			}catch(\Exception $e){
				return Response::generateError($e->getMessage(). ' -> ' . $e->getTraceAsString()); 
			}
        }
        return Response::generateSuccessData($up_result);
    }

}
